package com.car.slave.im.util;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

public class QiuniuUtil {
	
	public interface UploadFileCallback {
		void uploadResult(boolean success, String url);
	}

	public static final UploadManager sUploadManager = new UploadManager();
	
	private Context context;
	private String filePath;
	private UploadFileCallback ufCallback;
	
	public QiuniuUtil(Context context, String filePath, UploadFileCallback ufCallback) {
		super();
		this.context = context;
		this.filePath = filePath;
		this.ufCallback = ufCallback;
	}
	
	public void upload() {
		if (isExpires() || TextUtils.isEmpty(getToken())) {
			requestToken();
		} else {
			uploadFile();
		}
	}
	
	private boolean isExpires() {
		if (System.currentTimeMillis() - uploadTokenTime() >= 25 * 60 * 1000) {
			return true;
		}
		return false;
	}
	
	private void requestToken() {
		final String url = "http://test.api.chezhil.com/service/upload/upload-token?type=test";
		StringRequest request = new StringRequest(url, new Listener<String>() {
			@Override
			public void onResponse(String response) {
				String uploadToken = null;
				try {
					JSONObject obj = new JSONObject(response);
					if (obj.optInt("code") == 200) {
						uploadToken = obj.optJSONObject("data").optString("upload_token");
						saveUploadToken(uploadToken);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					uploadToken = null;
				}
				if (null == uploadToken) {
					ufCallback.uploadResult(false, null);
				} else {
					uploadFile();
				}
			}
		}, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				ufCallback.uploadResult(false, null);
			}
		});
		Volley.newRequestQueue(context).add(request);
	}
	
	private void uploadFile() {
		File f = new File(filePath);
		sUploadManager.put(filePath, f.getName(), getToken(), new UpCompletionHandler() {
			@Override
			public void complete(String key, ResponseInfo info, JSONObject response) {
				if (info.isOK()) {
					ufCallback.uploadResult(true, "http://7xjif7.dl1.z0.glb.clouddn.com/" + key);
				} else {
					ufCallback.uploadResult(false, null);
				}
			}
		}, null);
	}
	
	// 七牛的token更新时间
	private long uploadTokenTime() {
		SharedPreferences pre = context.getSharedPreferences("qiuNiu", Context.MODE_PRIVATE);
		return pre.getLong("uploadTokenTime", 0);
	}
	
	// 保存token
	private void saveUploadToken(String token) {
		if (null == token) {
			return;
		}
		uploadTokenTime();
		SharedPreferences.Editor editor = context.getSharedPreferences("qiuNiu", Context.MODE_PRIVATE).edit();
		editor.putString("token", token).commit();
	}
	
	// 获取token
	private String getToken() {
		SharedPreferences pre = context.getSharedPreferences("qiuNiu", Context.MODE_PRIVATE);
		return pre.getString("token", "");
	}
}
